package scanner.impl;

import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import pojo.Customer;
import scanner.DataScanner;

public class DataScannerImpl implements DataScanner {
	private InputStream in;
	private Scanner scaner;
	
	public DataScannerImpl(InputStream in) {
		super();
		this.in = in;
		scaner=new Scanner(in,"UTF-8");
		
	}

	public List<Customer> scann() throws ParseException {
		
		List<String> list=preScan();
		List<Customer> listCustomer=new ArrayList<Customer>();
		
		String  idFormat="^[1-9][0-9]*";
		String nameFormat="^[a-zA-Z][a-z]";
		String emailFormat="@(qq)||(163).com";
		String sexFormat="true||false";
		String birthdayFormat="^(19|20)\\d{2}-(1[0-2]|0?[1-9])-(0?[1-9]|[1-2][0-9]|3[0-1])";
		for(int i=0;i<list.size();i++)
		{
			String[] strOfList=list.get(i).split("[\\s]+");
			Pattern p1=Pattern.compile(idFormat);
			Matcher m1=p1.matcher(strOfList[0]);
			if(m1.find())
			{
				Pattern p2=Pattern.compile(nameFormat);
				Matcher m2=p2.matcher(strOfList[1]);
				if(m2.find())
				{
					if(strOfList[2].startsWith(strOfList[1])!=true)
					{
						continue;
					}
					else
					{
						Pattern p3=Pattern.compile(emailFormat);
						Matcher m3=p3.matcher(strOfList[2].substring(strOfList[1].length(), strOfList[2].length()));
						if(m3.find())
						{
							Pattern p4=Pattern.compile(sexFormat);
							Matcher m4=p4.matcher(strOfList[3]);
							if(m4.find())
							{
								Pattern p5=Pattern.compile(birthdayFormat);
								Matcher m5=p5.matcher(strOfList[4]);
								if(m5.find())
								{
									String[] dataStr={strOfList[0],strOfList[1],strOfList[3],strOfList[2],strOfList[4]};
									Customer temp=this.dataGet(dataStr);
									listCustomer.add(temp);
								}
								else
								{
									continue;
								}
							}
							else 
							{
								continue;
							}
						}
						else 
						{
							continue;
						}
						
					}
				}
				else
					continue;
			}
			else
			{
				continue;
			}
			
		}
		return listCustomer;
	}
	private Customer dataGet(String[] dataStr) throws ParseException {
		// TODO Auto-generated method stub
		Customer temp=new Customer();
		temp.setId(Integer.parseInt(dataStr[0]));
		temp.setName(dataStr[1]);
		boolean sex=true;
		if(dataStr[3].equals("false"))
			sex=false;
		temp.setSex(sex);
		SimpleDateFormat sdf2=new SimpleDateFormat("yyyy-MM-dd");
		Date date=sdf2.parse(dataStr[4]);
		temp.setBirth(date);
		temp.setEmail(dataStr[4]);
		return temp;
	}

	private List<String> preScan(){
		List<String> list=new ArrayList<String>();
		while(scaner.hasNext()){
			list.add(scaner.nextLine());
		}
		return list;
	}
	
	
	

}
